//
//  RegisterViewController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/2/26.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "RegisterViewController.h"
#import "NSString+ZC_Regex.h"
#import <AVOSCloud/AVOSCloud.h>
#import <Masonry.h>
#import "MyImageView.h"


#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height


@interface RegisterViewController ()<UIImagePickerControllerDelegate,UITextFieldDelegate,UINavigationControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic,strong) UITextField *emailTF;
@property (nonatomic,strong) UITextField *userPwdTF;
@property (nonatomic,strong) UITextField *confirmPwdTF;
@property (nonatomic,strong) UITextField *userTypeTF;
@property (nonatomic,strong) MyImageView *iconView;
@property (nonatomic,strong) UIPickerView *pickerV;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addViews];
    self.navigationItem.title = @"注册";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(didClickLeftBtn:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStyleDone target:self action:@selector(didClickRightBtn:)];
}

//左边按钮点击事件
- (void)didClickLeftBtn:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//右边按钮点击事件
- (void)didClickRightBtn:(UIBarButtonItem *)sender
{
    if(![self.emailTF.text isEmail])
    {
        [self addAlert:@"请输入正确的邮箱"];
    }else if([self.userPwdTF.text isEqualToString:@""] && [self.userPwdTF.text isEqualToString:@" "])
    {
        [self addAlert:@"密码不能为空"];
        
    }else if(![self.userPwdTF.text isEqualToString:self.confirmPwdTF.text])
    {
        [self addAlert:@"两次输入密码不一致"];
    }else
    {
        //将头像保存成NSData类型的数据，以百分之二十的比例
        NSData *imageData = UIImageJPEGRepresentation(self.iconView.image, .2f);
        //将NSData类型的数据保存成AVFile
        AVFile *imageFile = [AVFile fileWithData:imageData];
        //新建AVUser 对象实例
        AVUser *user = [AVUser user];
        user.username = self.emailTF.text;
        user.password = self.userPwdTF.text;
        user.email = self.emailTF.text;
        [user setObject:imageFile forKey:@"Picture"];
        [user setObject:self.userTypeTF.text forKey:@"userType"];
        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                // 注册成功
                [self addAlert:@"注册成功"];
                
            } else {
                // 失败的原因可能有多种，常见的是用户名已经存在。
                [self addAlert:@"注册失败，邮箱已经被注册"];
            }
        }];
    }
    
}


#pragma mark view的触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.emailTF resignFirstResponder];
    [self.userPwdTF resignFirstResponder];
    [self.confirmPwdTF resignFirstResponder];
    [self.userTypeTF resignFirstResponder];
}

#pragma mark TextField的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    return YES;
}



//弹框
- (void)addAlert:(NSString *)message
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *isOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([message isEqualToString:@"注册成功"])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [alert addAction:isOK];
    [self presentViewController:alert animated:YES completion:nil];
}


//页面布局
- (void)addViews
{
    //头像
    self.iconView = [[MyImageView alloc]initWithImage:[UIImage imageNamed:@"head"]];
    self.iconView.layer.masksToBounds = YES;
    self.iconView.layer.cornerRadius = kHeight * 0.065;
    [self.view addSubview:self.iconView];
    self.iconView.userInteractionEnabled = YES;
    [self.iconView MyTarget:self Action:@selector(getPicture)];
    
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(kHeight * 0.13, kHeight * 0.13));
        make.top.equalTo(self.view).offset(kHeight * 0.12);
        make.centerX.equalTo(self.view);
        
    }];
   
    UILabel *label = [[UILabel alloc] init];
    [self.view addSubview:label];
    label.text = @"点击上图选择头像";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.27);
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.6, 30));
    }];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.emailTF = [[UITextField alloc] init];
    self.emailTF.placeholder = @"请输入邮箱";
    self.emailTF.layer.borderWidth = 0.5;
    self.emailTF.layer.cornerRadius = 5;
    self.emailTF.delegate = self;
    [self.view addSubview:self.emailTF];
    [self.emailTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.32);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.9, 40));
    }];
    
    self.userPwdTF = [[UITextField alloc] init];
    self.userPwdTF.placeholder = @"请输入密码";
    self.userPwdTF.layer.borderWidth = 0.5;
    self.userPwdTF.layer.cornerRadius = 5;
    self.userPwdTF.delegate = self;
    self.userPwdTF.secureTextEntry = YES;
    [self.view addSubview:self.userPwdTF];
    [self.userPwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.4);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.9, 40));
    }];
    
    self.confirmPwdTF = [[UITextField alloc] init];
    self.confirmPwdTF.placeholder = @"请再次输入密码";
    self.confirmPwdTF.layer.borderWidth = 0.5;
    self.confirmPwdTF.layer.cornerRadius = 5;
    self.confirmPwdTF.delegate = self;
    self.confirmPwdTF.secureTextEntry = YES;
    [self.view addSubview:self.confirmPwdTF];
    [self.confirmPwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.48);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.9, 40));
    }];
    
    self.userTypeTF = [[UITextField alloc] init];
    self.userTypeTF.text = @"普通用户";
    self.userTypeTF.layer.borderWidth = 0.5;
    self.userTypeTF.layer.cornerRadius = 5;
    self.userTypeTF.delegate = self;
    [self.view addSubview:self.userTypeTF];
    [self.userTypeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.56);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.9, 40));
    }];
    
    //添加一个pickerView做为userTypeTF的inputView
    self.pickerV = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    self.pickerV.backgroundColor = [UIColor whiteColor];
    self.pickerV.delegate = self;
    self.pickerV.dataSource = self;
    self.userTypeTF.inputView = self.pickerV;
    self.pickerV.backgroundColor = [UIColor blueColor];
}


#pragma mark 点击选择头像
// 点击选取图片
- (void)getPicture{
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本地" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}


// 相册代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    self.iconView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
    
}


#pragma mark pickerView的代理
//设置滚轮的个数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//设置滚轮的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 2;
}

//滚轮显示的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(row == 1)
    {
        self.userTypeTF.text = @"医生";
        return @"医生";
    }
    else
    {
        self.userTypeTF.text = @"普通用户";
        return @"普通用户";
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
